<template>
  <el-dialog v-model="dialogVisible" :title="title" width="80%" class="intention-dialog">
    <div class="dialog-content">
      <el-form ref="form" :model="formData" label-width="80px" class="intention-form">
        <div class="conditions-header">
          <span class="conditions-title">
            <Icon icon="ep:warning-filled" class="required-icon" />
            同时满足下列条件
          </span>
          <el-button type="primary" @click="handleAdd" class="add-btn">
            <Icon icon="ep:plus" class="btn-icon" />
            添加条件
          </el-button>
        </div>

        <el-form-item class="content-item">
          <template v-for="(formItem, index) in formData.ivrIntentionlabelQueryDOList" :key="index">
            <div class="condition-card">
              <el-row class="condition-row" :gutter="10">
                <el-col :span="8">
                  <div class="form-field">
                    <label class="field-label">条件类型</label>
                    <el-select
                      v-model="formItem.selectType"
                      placeholder="请选择条件"
                      @change="fieldChange(formItem, index)"
                      class="enhanced-select"
                    >
                      <el-option
                        v-for="(item, idx) in matchTypeOptin"
                        :key="idx"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </el-col>

                <el-col
                  :span="7"
                  v-if="formItem.selectType && formItem.selectType != 7 && formItem.selectType != 8"
                >
                  <div class="form-field">
                    <label class="field-label">匹配符号</label>
                    <el-select
                      v-model="formItem.query"
                      placeholder="请选择条件"
                      class="enhanced-select"
                    >
                      <el-option
                        v-for="(item, idx) in formItem.selectType == 9
                          ? matchSymbolsOption2
                          : matchSymbolsOption"
                        :key="idx"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </el-col>

                <el-col :span="16" v-if="formItem.selectType == 7">
                  <div class="form-field">
                    <label class="field-label">包含条件</label>
                    <el-select
                      v-model="formItem.value"
                      placeholder="请选择"
                      class="enhanced-select"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </el-col>

                <el-col
                  :span="8"
                  v-if="formItem.selectType && formItem.selectType != 7 && formItem.selectType != 8"
                >
                  <div class="form-field">
                    <label class="field-label">数值</label>
                    <el-select
                      v-model="formItem.value"
                      placeholder="请选择条件"
                      v-if="formItem.selectType == 9"
                      class="enhanced-select"
                    >
                      <el-option
                        v-for="(item, idx) in endOption"
                        :key="idx"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <el-input-number
                      v-else
                      v-model="formItem.value"
                      :min="1"
                      :max="1000"
                      class="enhanced-input-number"
                    />
                  </div>
                </el-col>

                <el-col :span="1" class="delete-col">
                  <el-button type="danger" text @click="del(index)" class="delete-btn">
                    <Icon icon="ep:delete" />
                  </el-button>
                </el-col>
              </el-row>

              <el-row v-if="formItem.selectType == 7" class="keywords-row">
                <el-col :span="22">
                  <div class="form-field">
                    <label class="field-label">关键词</label>
                    <el-input
                      v-model.trim="formItem.keys"
                      type="textarea"
                      maxlength="500"
                      show-word-limit
                      placeholder="多个','分割"
                      class="enhanced-textarea"
                    />
                  </div>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-form-item>

        <el-divider class="section-divider" />

        <div class="label-section">
          <div class="label-header">
            <Icon icon="ep:price-tag" class="required-icon" />
            将意向等级标签设置为
          </div>
          <el-select v-model="formData.labelType" placeholder="请选择" class="label-select">
            <el-option
              v-for="dict in levelOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            >
              <el-tag
                :disable-transitions="false"
                :style="{
                  background: dict.bgColor,
                  color: dict.textColor,
                  marginRight: '10px',
                  border: 'none',
                  cursor: 'pointer',
                  paddingRight: '9px'
                }"
              >
                {{ dict.name }}
              </el-tag>
            </el-option>
          </el-select>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button type="primary" @click="submit" :disabled="loading" class="submit-btn">
          <Icon icon="ep:check" class="btn-icon" />
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import {
  createIntentionLabel,
  updateIntentionLabel,
  getIntentionLabelDetail
} from '@/api/call/ivr/index'

const dialogVisible = ref(false)
const title = ref('添加规则')
const intentionId = ref(null)
const formData = reactive({
  id: '',
  labelType: '',
  flowId: '',
  ivrIntentionlabelQueryDOList: []
})
const loading = ref(false)

const endOption = [
  {
    label: '肯定',
    value: '1'
  },
  {
    label: '否定',
    value: '2'
  },
  {
    label: '拒绝',
    value: '3'
  },
  {
    label: '未识别',
    value: '4'
  }
]

const matchTypeOptin = [
  {
    label: '命中所有问题',
    value: 1
  },
  {
    label: '命中业务问题',
    value: 2
  },
  {
    label: '肯定次数',
    value: 3
  },
  {
    label: '拒绝次数',
    value: 4
  },
  {
    label: '客户讲话次数',
    value: 5
  },
  {
    label: '通话时长',
    value: 6
  },
  {
    label: '客户通话内容',
    value: 7
  },
  {
    label: '走完主流程',
    value: 8
  },
  {
    label: '客户说最后一句',
    value: 9
  }
]

// 匹配符号
const matchSymbolsOption = [
  {
    label: '>=',
    value: 2
  },
  {
    label: '<=',
    value: 3
  }
]

const matchSymbolsOption2 = [
  {
    label: '=',
    value: 1
  }
]

const levelOptions = ref([])

const options = [
  {
    label: '包含1个以上',
    value: 1
  },
  {
    label: '包含2个以上',
    value: 2
  },
  {
    label: '包含3个以上',
    value: 3
  },
  {
    label: '包含4个以上',
    value: 4
  },
  {
    label: '包含5个以上',
    value: 5
  },
  {
    label: '包含6个以上',
    value: 6
  },
  {
    label: '包含7个以上',
    value: 7
  },
  {
    label: '包含8个以上',
    value: 8
  },
  {
    label: '包含9个以上',
    value: 9
  },
  {
    label: '包含10个以上',
    value: 10
  },
  {
    label: '包含全部',
    value: 0
  }
]

const fieldChange = (item, index) => {
  if (item.selectType == 9) {
    formData.ivrIntentionlabelQueryDOList[index].query = 1
  } else if (item.selectType == 7 || item.selectType == 8) {
    if (item.selectType == 7) {
      formData.ivrIntentionlabelQueryDOList[index].value = 1
    }
  } else {
    formData.ivrIntentionlabelQueryDOList[index].query = 2
  }
}

// 添加条件
const handleAdd = () => {
  formData.ivrIntentionlabelQueryDOList.push({
    selectType: '', //匹配类型
    query: '', //匹配符号
    value: '', //配置值
    keys: '' //selectType  7 匹配关键词
  })
}

// 删除条件
const del = (index) => {
  formData.ivrIntentionlabelQueryDOList.splice(index, 1)
}

const emit = defineEmits(['success'])

const open = async (type, id, flowId, option) => {
  levelOptions.value = option
  formData.flowId = flowId
  formData.labelType = ''
  formData.ivrIntentionlabelQueryDOList = []
  if (id) {
    title.value = '编辑规则'
    const data = await getIntentionLabelDetail(id)
    formData.id = data.id
    formData.labelType = data.labelType
    formData.ivrIntentionlabelQueryDOList = data.ivrIntentionlabelQueryDOList
  } else {
    title.value = '添加规则'
  }
  formData.id = id
  dialogVisible.value = true
}

const submit = async () => {
  if (formData.labelType == '') {
    ElMessage.warning('请选择将意向等级标签')
    return
  }
  if (formData.ivrIntentionlabelQueryDOList.length == 0) {
    ElMessage.warning('请配置条件')
    return
  }
  const isType = formData.ivrIntentionlabelQueryDOList.some((item) => item.selectType == '')
  if (isType) {
    ElMessage.warning('请检查条件')
    return
  }
  const isType2 = formData.ivrIntentionlabelQueryDOList.some(
    (item) => item.selectType == 7 && item.keys == ''
  )
  if (isType2) {
    ElMessage.warning('请输入内容关键字，多个","分割')
    return
  }
  try {
    loading.value = true
    if (formData.id) {
      const data = cloneDeep(formData)
      data.ivrIntentionlabelQueryDOList.forEach((element) => {
        delete element.id
      })
      await updateIntentionLabel(data)
    } else {
      await createIntentionLabel(formData)
    }
    ElMessage.success('操作成功')
    emit('success')
    dialogVisible.value = false
  } finally {
    loading.value = false
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.intention-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
    color: white;
    padding: 20px 24px;
  }

  :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
    font-size: 18px;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
  }
}

.dialog-content {
  padding: 24px;
  background: #f8fafc;
}

.intention-form {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.conditions-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid rgba(0, 82, 204, 0.1);
}

.conditions-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.required-icon {
  color: #ef4444;
  font-size: 16px;
}

.add-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

.content-item {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}

.condition-card {
  background: rgba(0, 82, 204, 0.02);
  border: 1px solid rgba(0, 82, 204, 0.1);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(0, 82, 204, 0.05);
    border-color: rgba(0, 82, 204, 0.2);
    box-shadow: 0 2px 8px rgba(0, 82, 204, 0.1);
  }
}

.condition-row {
  align-items: end;
}

.keywords-row {
  margin-top: 12px;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.field-label {
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
}

.enhanced-select,
.enhanced-input-number {
  :deep(.el-input__wrapper) {
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 2px 8px rgba(0, 82, 204, 0.2);
    }
  }
}

.enhanced-textarea {
  :deep(.el-textarea__inner) {
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 2px 8px rgba(0, 82, 204, 0.1);
    }

    &:focus {
      box-shadow: 0 2px 8px rgba(0, 82, 204, 0.2);
    }
  }
}

.delete-col {
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn {
  color: #ef4444;
  padding: 8px;
  border-radius: 6px;

  &:hover {
    background: rgba(239, 68, 68, 0.1);
  }
}

.section-divider {
  margin: 24px 0;
  border-color: rgba(0, 82, 204, 0.1);
}

.label-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.label-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.label-select {
  width: 300px;

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: white;
  border-top: 1px solid rgba(0, 82, 204, 0.1);
}

.cancel-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  border-radius: 8px;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.submit-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .intention-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 20px auto;
    }
  }

  .dialog-content {
    padding: 16px;
  }

  .intention-form {
    padding: 16px;
  }

  .conditions-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .condition-row {
    :deep(.el-col) {
      margin-bottom: 12px;
    }
  }

  .label-select {
    width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dialog-content {
    background: #1f2937;
  }

  .intention-form {
    background: #374151;
  }

  .conditions-title {
    color: #f9fafb;
  }

  .field-label {
    color: #d1d5db;
  }

  .label-header {
    color: #e5e7eb;
  }

  .condition-card {
    background: rgba(0, 82, 204, 0.1);
  }
}
</style>
